﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Extension {
  public static class RandomExt {
    /// <summary>
    /// 随机返回 ture 或 false
    /// </summary>
    /// <param name="random"></param>
    /// <returns></returns>
    public static bool NextBool(this Random random) {
      return random.NextDouble() > 0.5;
    }
    /// <summary>
    /// 随机返回给定枚举类型的一个枚举值
    /// </summary>
    /// <typeparam name="T">给定的枚举类型</typeparam>
    /// <param name="random"></param>
    /// <returns></returns>
    public static T NextEnum<T>(this Random random) where T : struct {
      Type type = typeof(T);
      if (!type.IsEnum) throw new InvalidOperationException();

      Array array = Enum.GetValues(type);
      int index = random.Next(array.GetLowerBound(0), array.GetUpperBound(0) + 1);
      return (T)array.GetValue(index);
    }
    /// <summary>
    /// 随机返回一个给定长度的byte[] 数组
    /// </summary>
    /// <param name="random"></param>
    /// <param name="length">给定的长度</param>
    /// <returns></returns>
    public static byte[] NextBytes(this Random random, int length) {
      byte[] bytes = new byte[length];
      random.NextBytes(bytes);

      return bytes;
    }

    /// <summary>
    /// 随机返回一个指定范围内的DateTime结构
    /// </summary>
    /// <param name="random"></param>
    /// <param name="min"></param>
    /// <param name="max"></param>
    /// <returns></returns>
    public static DateTime NextDateTime(this Random random, DateTime min, DateTime max) {
      long ticks = min.Ticks + (long)((max.Ticks - min.Ticks) * random.NextDouble());

      return new DateTime(ticks);
    }

    /// <summary>
    /// 随机返回一个与指定正则表达式匹配的密码（未实现）
    /// </summary>
    /// <param name="random"></param>
    /// <param name="pattern">正则表达式</param>
    /// <returns></returns>
    public static string NextPassword(this Random random, string pattern) {
      throw new NotImplementedException();
    }
  }
}
